package com.zhu.rpc.server.handler;

import com.zhu.rpc.JsonUtil;
import com.zhu.rpc.MsgType;
import com.zhu.rpc.msgBean.RpcRequestBean;
import com.zhu.rpc.server.ResponseMessageCache;
import com.zhu.rpc.server.RpcProtocolProviderBean;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RpcMsgDecode extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

//        msg
        ByteBuf in = ((ByteBuf)msg);
        //取前两位判定消息的类别
        String str = in.toString(CharsetUtil.UTF_8);
        System.out.println("收到:"+str);
        int type = Integer.parseInt(str.substring(0,2));
        MsgType msgType = MsgType.getTypeById(type);
        switch (msgType){
            case callReq:
                msg = JsonUtil.getObj(str.substring(2),RpcProtocolProviderBean.class);
                ctx.fireChannelRead(msg);
                break;
            case heartBeat:
                //默认不返回
//                msg = JsonUtil.getObj(str.substring(2),msgType.msgBean);
//                ctx.writeAndFlush(String.valueOf(MsgType.heartBeat.id));
                break;
            case callReReq:
                RpcProtocolProviderBean req = JsonUtil.getObj(str.substring(2), RpcProtocolProviderBean.class);
                String respMsg = ResponseMessageCache.getResponse(req.getMsgId());
                if (respMsg == null){

                    // TODO 代表之前的消息可能没有收到，不处理 如果调用了函数处理可能会造成重复处理，并且如果在callReq中判断是否接收消息，是否是不必要的性能损耗？
                }else {
                    ctx.writeAndFlush(respMsg);
                }
                break;
//            case init:
//                msg = JsonUtil.getObj(str.substring(2),msgType.msgBean);
//                ctx.fireChannelRead(msg);
//                break;
            default:
                ctx.fireChannelRead(msg);
                break;
        }

    }
}
